package com.tsd.core.config;

import com.tsd.core.constants.ConfigKeyConstants;
import com.tsd.core.utils.ConfigUtil;
import com.tsd.core.utils.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description:
 * @Author Hillpool
 * @Date 2019/3/11 16:07
 * @Modefied By:
 */
public class Config {

    public static final Logger LOGGER = LoggerFactory.getLogger(Config.class);
    public static boolean debug = true;
    /**
     * 参数Map
     */
    private static Map<String, String> paramsMap = null;

    public static String getClassFilePath() {
        return Objects.requireNonNull(Config.class.getResource("/")).getPath();
    }

    /**
     * 获取Tomcat的webapps目录
     *
     * @return
     */
    public static String getWebAppsDir() {
        String s = Objects.requireNonNull(Config.class.getResource("/")).getPath();
        s = s.replaceAll("\\\\", "/");
        int index = s.lastIndexOf("/");
        if (index == s.length() - 1) {
            s = s.substring(0, index);//剔除最后一个/
        }
        index = s.lastIndexOf("/");
        s = s.substring(0, index);//剔除当前classes
        index = s.lastIndexOf("/");
        s = s.substring(0, index);//剔除当前web-inf
        index = s.lastIndexOf("/");
        s = s.substring(0, index + 1);//剔除当前appname
        return s;
    }

    /**
     * 重载参数
     */
    public static void reloadParameter() {
        loadParamsNew(true);
    }

    public static String getParameterValue(String key) {
        loadParamsNew(false);
        if (paramsMap != null) {
            return paramsMap.get(key);
        } else {
            return null;
        }
    }


    /**
     * 加载参数
     *
     * @param reload
     */
    private static void loadParams(boolean reload) {
        if (paramsMap == null || reload) {
            String classURL = Objects.requireNonNull(ConfigUtil.class.getResource("/config")).getPath();
            try {
                classURL = URLDecoder.decode(classURL, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
            }
            File classFileDir = new File(classURL);
            File[] list = classFileDir.listFiles();
            if (list != null) {
                paramsMap = new LinkedHashMap<>();
                for (File f : list) {
                    if (f.getName().toLowerCase().endsWith(".xml")) {
                        Map<String, String> oneMap = ConfigUtil.loadMapFromXMLFullPath(f.getAbsolutePath(), true);
                        paramsMap.putAll(oneMap);
                    }
                }
            }
        }
    }

    /**
     * 加载参数
     *
     * @param reload
     */
    private static void loadParamsNew(boolean reload) {
        if (paramsMap == null || reload) {
            paramsMap = new LinkedHashMap<>();
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] sqlResources;
            try {
                sqlResources = resolver.getResources(ConfigKeyConstants.CONFIG_CLASSPATH);
                for (Resource resource : sqlResources) {
                    String path = resource.getURL().getPath();
                    File classFile = new File(path);
                    if (classFile.isFile()) {
                        if (classFile.getName().toLowerCase().endsWith(".xml")) {
                            Map<String, String> oneMap = ConfigUtil.loadMapFromXMLFullPath(classFile.getAbsolutePath(), true);
                            paramsMap.putAll(oneMap);
                        }
                        continue;
                    }
                    File[] list = classFile.listFiles();
                    if (list != null) {
                        for (File file : list) {
                            if (file.getName().toLowerCase().endsWith(".xml")) {
                                Map<String, String> oneMap = ConfigUtil.loadMapFromXMLFullPath(file.getAbsolutePath(), true);
                                paramsMap.putAll(oneMap);
                            }
                        }
                    }
                }
            } catch (IOException e) {
                LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
            }
        }
    }
}
